import 'dart:async';

import 'package:flutter/material.dart';

import '../component/loading_component.dart';
import 'continue_scan_page.dart';

///
/// ProjectName: ncmflutterDev
/// Author: lizhi
/// CreateDate: 2022/4/19 3:20 下午
/// Copyright: ©2022 NEW CORE Technology Co. Ltd. All rights reserved.
/// Description: 连续扫码示例页面
///
class ContinueScanExample extends StatefulWidget {
  const ContinueScanExample({Key? key, this.isPDAModel = false})
      : super(key: key);

  /// 是否是PDA模式  显示UI跟摄像头扫码有差异
  /// 摄像头模式不启用激光扫码监听
  final bool isPDAModel;

  static Future push(BuildContext context, {isPDAModel = false}) =>
      Navigator.of(context).push(MaterialPageRoute(
        settings: const RouteSettings(name: 'ContinueScanExample'),
        builder: (context) => ContinueScanExample(isPDAModel: isPDAModel),
      ));

  @override
  _ContinueScanExampleState createState() => _ContinueScanExampleState();
}

class _ContinueScanExampleState extends State<ContinueScanExample> {
  Completer<InfoItemUI?>? _completer;
  final InfoListController infoListController = InfoListController();

  /// 用于防重复判断
  List<String> infoIdList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ContinueScanPage<InfoItemUI>(
        isPDAModel: widget.isPDAModel,
        infoListController: infoListController,
        getInfoItemWidget: (infoData, int index, int totalLength) {
          return _getInfoItem(infoData);
        },
        onScanResult:
            (String result, List<InfoItemUI> infoList, bool showLoading) async {
          infoIdList = infoList.map((e) => e.id).toList();

          /// 返回信息条目UIModel
          _completer = Completer<InfoItemUI?>();
          _parseScanResult(result);
          return _completer!.future;
        },

        /// 默认底部按钮点击确认
        onConfirm: (List<InfoItemUI> infoList) {
          ///点击确定  处理数据 pop页面
          var infIds = infoList.map((e) => e.id).toList();
          Navigator.of(context).pop(infIds);
        },

        /// 支持自定义底部布局，替代默认的底部按钮
        // customBottomWidget: (List<InfoItemUI> infoList) {
        //   return Container(
        //     color: Colors.greenAccent,
        //     child: Text('自定义底部布局，替代默认的底部按钮, 信息列表长度：${infoList.length}'),
        //   );
        // },
      ),
    );
  }

  /// 解析QR内容获取关键信息
  void _parseScanResult(String? qrContent) {
    /// 解析二维码内容
    _onGetQrInfo(qrContent);

    // QRCodeParser.parse(
    //   qrContent,
    //   onMaterial: (model) {
    //     var seqNumber = model.sn;
    //     _onGetQrInfo(seqNumber);
    //   },
    //   onError: (error) {
    //     _completer?.complete(null);
    //     toast(context, error);
    //   },
    // );
  }

  /// 使用关键信息 进行数据筛选或接口调用
  ///
  void _onGetQrInfo(String? key) {
    if (key == null) {
      _completer?.complete(null);
      return;
    }
    if (infoIdList.contains(key)) {
      toast(context, '已包含');
      _completer?.complete(null);
      return;
    }

    /// do something  调接口 或进行数据筛选
    var infoUI = InfoItemUI(
      key,
      desc: 'desc',
      title: key,
    );
    _completer!.complete(infoUI);
  }

  Widget _getInfoItem(InfoItemUI infoData) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(left: 16, top: 10, bottom: 10),
      margin: const EdgeInsets.only(bottom: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: Text(
                  infoData.title,
                  style: TextStyle(
                    color: Colors.blueAccent,
                    fontSize: 12,
                  ),
                ),
              ),
              InkWell(
                onTap: () {
                  infoListController.remove(infoData);
                },
                child: Padding(
                  padding: const EdgeInsets.only(
                      left: 16, top: 6, right: 16, bottom: 6),
                  child: Icon(Icons.delete_outline_outlined),
                ),
              )
            ],
          ),
          if (infoData.desc?.isNotEmpty == true)
            Text(
              infoData.desc!,
              style: TextStyle(
                color: Colors.black87,
                fontSize: 12,
              ),
            ),
        ],
      ),
    );
  }
}

class InfoItemUI {
  InfoItemUI(this.id, {this.desc, required this.title});

  /// 第一行显示信息  物料SN:searchKey、 订单编号：searchKey
  String title;

  /// 第二行   批量编号：xxx
  String? desc;

  ///
  String id;
}
